<template>
  <div class="app-container">
    <div style="margin-bottom: 4px;">
      <!-- 搜索筛选 -->
      <el-select v-model="searchForm.dateType" @change="selectTypeChange" placeholder="请选择类型">
        <el-option v-for="b in selecDateList" :key="b.id" :lable="b.id" :value="b.name"></el-option>
      </el-select>
      <el-select v-model="searchForm.type" @change="selectTypeChange" placeholder="请选择统计类型">
        <el-option v-for="s in selecTypeList" :key="s.id" :lable="s.id" :value="s.name"></el-option>
      </el-select>
    </div>

    <div class="title">
      <label>{{title}}</label>
    </div>
    <!-- :cell-style="cellStyle" :header-cell-style="headCellStyle"-->
    <el-table ref="multipleTable" :data="list" v-loading="listLoading" element-loading-text="Loading" show-summary :summary-method="getSum" border fit highlight-current-row :span-method="objectSpanMethod"
      >

     <el-table-column label="组别" prop="groupName">
       <template slot-scope="scope">
         {{scope.row.groupName}}
       </template>
     </el-table-column>
      <el-table-column label="销售" prop="saleName">
        <template slot-scope="scope">
          {{scope.row.saleName}}
        </template>
      </el-table-column>
      <el-table-column label="00:00 到 09:00" prop="one">
        <template slot-scope="scope">
          {{scope.row.one}}
        </template>
      </el-table-column>
      <el-table-column label="09:00 到 12:00" prop="two">
        <template slot-scope="scope">
          {{scope.row.two}}
        </template>
      </el-table-column>
      <el-table-column label="12:00 到 16:00" prop="three">
        <template slot-scope="scope">
          {{scope.row.three}}
        </template>
      </el-table-column>
      <el-table-column label="16:00 到 18:30" prop="four">
        <template slot-scope="scope">
          {{scope.row.four}}
        </template>
      </el-table-column>
      <el-table-column label="18:30 到 00:00" prop="five">
        <template slot-scope="scope">
          {{scope.row.five}}
        </template>
      </el-table-column>
      <el-table-column label="合计" prop="total">
        <template slot-scope="scope">
          {{scope.row.total}}
        </template>
      </el-table-column>

      <!--<el-table-column label="操作">
      </el-table-column>-->
    </el-table>
    <div slot="footer" class="dialog-footer">
      <el-button :type="pre" @click="preClick()" id="pre">{{pre}}</el-button>
      <el-button :type="net" @click="nextClick()" id="next">{{net}}</el-button>
    </div>
  </div>
</template>
<style lang="scss">
  .title{padding: 1% 0%;background: #FED966;}
  .title>label{margin-left: 1%;font-weight:100;color: red;font-size: 15px;}
  .el-table__body,.el-table__header th,.el-table__footer{text-align: center;}
  .el-table__footer-wrapper .is-leaf{background:#FED966;}
  .el-table__footer-wrapper .is-leaf>div{color: red;}
  .dialog-footer{margin-top: 1%;}

</style>
<script>
  import { callstatis } from '@/api/callstatist'
  export default {
    data() {
      return {
        name: 'callstatist',
        title:new Date().Format("yyyy-MM-dd"),
        selecDateList:[],
        selecTypeList:[],
        list: [],
        arrA:[],
        arrB:[],
        arrC:[],
        arrD:[],
        spanArr: [], // 一个空的数组，用于存放每一行记录的合并数
        pos: 0, // spanArr 的索引
        contentSpanArr: [],
        startTime: null,
        listLoading: true,
        formLabelWidth: '100px',
        searchForm: {
          dateType:'当天',
          type: '预约统计',
          page:0,
        },
        pre:'上一天',
        net:'下一天'
      }
    },
    created() {
      this.fetchData()
      this.initArr()
    },
    methods: {
      fetchData() {
        this.listLoading = true
        callstatis.getList(this.searchForm.dateType,this.searchForm.type,this.searchForm.page).then(response => {
          if(response.data!=undefined &&response.data.length>0){
            this.handList(response.data);
          } else {
            this.list = []
          }
          this.listLoading = false
        })
      },
      // 初始化
      initArr(){
        this.createArr(this.arrA,['曾欢','杨旭漫','林谋','吴曼盈'],'A')
        this.createArr(this.arrB,['方国','梁烨'],'B')
        this.createArr(this.arrC,['余秋蓉','彭晓祯','邹绮婷','谢俊英'],'C')
        this.createArr(this.arrD,['徐帝勇','郑梦仙','梁善涌'],'D')
        this.initSelect('预约统计,二次拨打统计'.split(","),this.selecTypeList);
        this.initSelect('当天,当月'.split(","),this.selecDateList);
      },
      initSelect(arr,list){
        arr.forEach((n, index) => {
          list.push({
            id: index,
            name: n
          });
        });
      },
      // 还原初始化
      clearArr(){
        this.arrA = [];
        this.arrB = []
        this.arrC = []
        this.arrD = []
        this.spanArr =[]
        this.pos = 0
        this.contentSpanArr = []
        this.createArr(this.arrA,['曾欢','杨旭漫','林谋','吴曼盈'],'A')
        this.createArr(this.arrB,['方国','梁烨'],'B')
        this.createArr(this.arrC,['余秋蓉','彭晓祯','邹绮婷','谢俊英'],'C')
        this.createArr(this.arrD,['徐帝勇','郑梦仙'],'D')
      },
      // 选择事件
      selectTypeChange(val){
          this.list = [];
          this.clearArr();
          this.fetchData();
          if(val.indexOf("天")!=-1){
            this.pre = "上一天"
            this.net = "下一天"
            this.title = new Date().Format("yyyy-MM-dd")
          }
        if(val.indexOf("月")!=-1){
          this.pre = "上一月"
          this.net = "下一月"
          this.title = new Date(this.title).Format("yyyy-MM")
        }
      },
      preClick(){
        this.searchForm.page -= 1
        if(this.pre.indexOf("月")!=-1){
          this.title = new Date(this.title).getFullYear()+"-"+(new Date(this.title).getMonth()>9?new Date(this.title).getMonth():"0"+new Date(this.title).getMonth());
        } else {
          this.title = callstatis.addDate(new Date(this.title),-1)
        }
        this.clearArr();
        this.fetchData();
      },
      nextClick(){
        this.searchForm.page += 1
        if(this.pre.indexOf("月")!=-1){
          let t = new Date(this.title).getMonth()+2;
          if(t>(new Date().getMonth()+1)){
            this.warnMsg("不能超过当前月")
            return ;
          }
          this.title = new Date(this.title).getFullYear()+"-"+(t>9?t:"0"+t);
        } else {
          this.title = callstatis.addDate(new Date(this.title),1)
        }
        this.clearArr();
        this.fetchData();
      },
      // 创建组别信息
      createArr(obj,arr,id){
        arr.forEach((n, index) => {
          obj.push({id:id,saleName:n,one:'',two:'',three:'',four:'',five:'',total:''});
        });
      },
      // 赋值操作
      setSale(arr,obj){
        let total = 0;
        for(let d in arr){
          if(obj.ttime!=undefined && d == obj.ttime ){
            arr[d] = obj.num
            total += obj.num;
          }
        }
        arr['total'] = parseInt((arr.total==""||arr.total=='合计')?0:arr.total) + parseInt(total);
      },
      // 获取组别信息
      getProper(myArr,name){
        return myArr.find((item,index,arr)=>{
          return item.saleName==name
        });
      },
      handList(data){
        for (let i of data) {
          if (this.arrA.filter(item => {return item.saleName == i.name }).length > 0 ) {
            this.handleArr(this.arrA, i, "A", "曾欢组");
          }
          if (this.arrB.filter(item => {
            return item.saleName == i.name
          }).length > 0) {
            this.handleArr(this.arrB, i, "B", "方国组");
          }
          if (this.arrC.filter(item => {
            return item.saleName == i.name
          }).length > 0 ) {
            this.handleArr(this.arrC, i, "C", "余秋蓉组");
          }
          if (this.arrD.filter(item => {
            return item.saleName == i.name
          }).length > 0 ) {
            this.handleArr(this.arrD, i, "D", "徐帝勇组");
          }
        }
        let tempArr =  this.arrA.concat(this.arrB,this.arrC,this.arrD);
        // 组装数据
        this.list= tempArr.filter((item,i)=>{
          if (i === 0) {
            this.spanArr.push(1);
            this.pos = 0;
            this.contentSpanArr.push(1);
            this.position = 0;
          } else {
            // 判断当前元素与上一个元素是否相同(第1和第2列)
            if (item.id === tempArr[i - 1].id) {
              this.spanArr[this.pos] += 1;
              this.spanArr.push(0);
            } else {
              this.spanArr.push(1);
              this.pos = i;
            }
          }
          if(item.groupName ==undefined){
            item.groupName = item.saleName+"组"
          }
          return  item.total!='合计'
        })
      },
      // 处理数据
      handleArr(arr,obj,id,name){
        let tmp = this.getProper(arr, obj.name)
        this.setSale(tmp, obj)
        tmp.groupName = name;
      },
      // 合并单元格
      objectSpanMethod({ row, column, rowIndex, columnIndex }){
        if (columnIndex === 0) {
          const _row = this.spanArr[rowIndex];
          const _col = _row > 0 ? 1 : 0;
          return {
            rowspan: _row,
            colspan: _col
          }
        }
      },
      // 汇总
      getSum(param){
        const {columns,data} = param;
        const sums = []
        let values = []
        if(columns.length>0 && data.length>0){
          columns.forEach((c,ind)=>{
            if(ind ===0){
              sums[ind] = '总计'
              return ;
            }
            if(ind >=3 || ind<=7) {
              values = data.map(item => Number(item[c.property]))
              if (!values.every(value => isNaN(value))) {
                sums[ind] = values.reduce((prev, curr) => {
                  const value = Number(curr)
                  if (!isNaN(value)) {
                    return prev + curr
                  } else {
                    return prev
                  }
                }, 0)
              } else {
                sums[ind] = ' '
              }
            }else{
              sums[ind] = '--'
            }
          })
         }
        return sums;
      },
      warnMsg(msg){
        this.$message({
          message: msg,
          type: 'warning'
        });
      }
    }
  }

</script>

<style scoped>

</style>
